package com.exam.gateway.filters;

import com.exam.auth.entiy.UserInfo;
import com.exam.auth.utils.JwtUtils;
import com.exam.common.until.CookieUtils;
import com.exam.gateway.config.FilterProperties;
import com.exam.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName : AuthFilter
 * @Description : 过滤器
 * @Author : WHB
 */
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class AuthFilter extends ZuulFilter{

    @Autowired
    private JwtProperties prop;

    @Autowired
    private FilterProperties FilterProp;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER -1; // 过滤器顺序
    }

    //是否过滤
    @Override
    public boolean shouldFilter() {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request对象
        HttpServletRequest request = ctx.getRequest();
        System.out.println(request);
        //获取请求路径
        String uri = request.getRequestURI();
        System.out.println(uri);
        //是否放行
        boolean isAllowPath = isAllowPath(uri);
        return !isAllowPath;
    }

    /**
     * 放行名单判断
     * @param uri
     * @return
     */
    private boolean isAllowPath(String uri) {
        for (String allwoPath : FilterProp.getAllowPaths()) {
            if (uri.startsWith(allwoPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 获取token
        String token = CookieUtils.getCookieValue(request, prop.getCookieName());
        if (token == null){
            token = request.getHeader("X-Token");
        }

        // 解析token
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            System.out.println(userInfo.toString());
        }catch (Exception e){
            System.out.println("拦截：：：：：：");
            //进行拦截
            ctx.setSendZuulResponse(false);
            //返回状态码  403表示没有权限
            ctx.setResponseStatusCode(403);
        }
        // 校验权限
        return null;
    }
}
